import React, { useState, useEffect } from "react";
import {
  Card,
  Descriptions,
  Divider,
  Typography,
  Table,
  Badge,
  Tag,
  Space,
  Alert,
} from "antd";
import {
  ClockCircleOutlined,
  EnvironmentOutlined,
  DesktopOutlined,
  InfoCircleOutlined,
  CodeOutlined,
} from "@ant-design/icons";
import {
  isDev,
  isProd,
  getMode,
  getApiBaseUrl,
  isMockEnabled,
} from "../utils/env";

const { Title, Text, Paragraph } = Typography;

interface BrowserInfo {
  key: string;
  name: string;
  value: string;
}

/**
 * 系统变量演示组件
 * 展示Vite环境变量、系统时间、浏览器信息等
 */
const SystemInfoDemo: React.FC = () => {
  const [currentTime, setCurrentTime] = useState(new Date());
  const [browserInfo, setBrowserInfo] = useState<BrowserInfo[]>([]);

  // 更新系统时间
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  // 获取浏览器信息
  useEffect(() => {
    const ua = navigator.userAgent;
    const browserData: BrowserInfo[] = [
      { key: "1", name: "用户代理", value: ua },
      { key: "2", name: "浏览器代号", value: navigator.appCodeName },
      { key: "3", name: "浏览器名称", value: navigator.appName },
      { key: "4", name: "浏览器版本", value: navigator.appVersion },
      { key: "5", name: "平台", value: navigator.platform },
      { key: "6", name: "浏览器引擎", value: detectEngine(ua) },
      { key: "7", name: "操作系统", value: detectOS(ua) },
      { key: "8", name: "是否在线", value: navigator.onLine ? "在线" : "离线" },
      { key: "9", name: "语言", value: navigator.language },
      {
        key: "10",
        name: "是否启用Cookie",
        value: navigator.cookieEnabled ? "是" : "否",
      },
      {
        key: "11",
        name: "是否支持DoNotTrack",
        value: navigator.doNotTrack ? "是" : "否",
      },
      {
        key: "12",
        name: "Web Worker",
        value: typeof Worker !== "undefined" ? "支持" : "不支持",
      },
      {
        key: "13",
        name: "WebSocket",
        value: typeof WebSocket !== "undefined" ? "支持" : "不支持",
      },
      { key: "14", name: "WebGL", value: detectWebGL() ? "支持" : "不支持" },
    ];

    setBrowserInfo(browserData);
  }, []);

  // 检测浏览器渲染引擎
  const detectEngine = (ua: string) => {
    if (ua.indexOf("Gecko") > -1 && ua.indexOf("KHTML") === -1) return "Gecko";
    if (ua.indexOf("KHTML") > -1)
      return ua.indexOf("WebKit") > -1 ? "WebKit" : "KHTML";
    if (ua.indexOf("Presto") > -1) return "Presto";
    if (ua.indexOf("Trident") > -1 || ua.indexOf("MSIE") > -1) return "Trident";
    if (ua.indexOf("EdgeHTML") > -1) return "EdgeHTML";
    if (ua.indexOf("Blink") > -1) return "Blink";
    return "未知";
  };

  // 检测操作系统
  const detectOS = (ua: string) => {
    if (ua.indexOf("Windows") > -1) return "Windows";
    if (ua.indexOf("Mac") > -1) return "macOS";
    if (ua.indexOf("Linux") > -1) return "Linux";
    if (ua.indexOf("Android") > -1) return "Android";
    if (
      ua.indexOf("iOS") > -1 ||
      ua.indexOf("iPhone") > -1 ||
      ua.indexOf("iPad") > -1
    )
      return "iOS";
    return "未知";
  };

  // 检测是否支持WebGL
  const detectWebGL = () => {
    try {
      const canvas = document.createElement("canvas");
      return (
        !!window.WebGLRenderingContext &&
        (canvas.getContext("webgl") || canvas.getContext("experimental-webgl"))
      );
    } catch (e) {
      return false;
    }
  };

  // 格式化日期函数
  const formatDate = (date: Date) => {
    const options: Intl.DateTimeFormatOptions = {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      hour12: false,
    };
    return new Intl.DateTimeFormat("zh-CN", options).format(date);
  };

  // 表格列定义
  const columns = [
    {
      title: "变量名",
      dataIndex: "name",
      key: "name",
      width: "30%",
      render: (text: string) => <Text code>{text}</Text>,
    },
    {
      title: "值",
      dataIndex: "value",
      key: "value",
    },
  ];

  // Vite环境变量数据
  const envVars = [
    { key: "1", name: "MODE", value: getMode(), description: "当前模式" },
    {
      key: "2",
      name: "DEV",
      value: isDev() ? "true" : "false",
      description: "是否为开发模式",
    },
    {
      key: "3",
      name: "PROD",
      value: isProd() ? "true" : "false",
      description: "是否为生产模式",
    },
    {
      key: "4",
      name: "VITE_ENABLE_MOCK",
      value: isMockEnabled() ? "true" : "false",
      description: "是否启用Mock数据",
    },
    {
      key: "5",
      name: "VITE_API_BASE_URL",
      value: getApiBaseUrl() || "未设置",
      description: "API基础URL",
    },
    {
      key: "6",
      name: "BASE_URL",
      value: import.meta.env.BASE_URL,
      description: "部署基础路径",
    },
  ];

  // 自定义环境变量
  const customEnvVars: Record<string, string> = {};
  Object.keys(import.meta.env).forEach((key) => {
    if (
      key.startsWith("VITE_") &&
      !["VITE_ENABLE_MOCK", "VITE_API_BASE_URL"].includes(key)
    ) {
      // 添加类型断言确保环境变量被当作字符串处理
      customEnvVars[key] = import.meta.env[
        key as keyof ImportMetaEnv
      ] as unknown as string;
    }
  });

  const customEnvVarsList = Object.keys(customEnvVars).map((key, index) => ({
    key: `custom-${index}`,
    name: key,
    value: customEnvVars[key],
  }));

  return (
    <div style={{ padding: "24px" }}>
      <Title level={2}>系统信息与环境变量</Title>

      <Alert
        message="敏感信息警告"
        description="此页面展示了系统和环境信息，可能包含敏感数据。在分享屏幕或截图时请注意隐去敏感信息。"
        type="warning"
        showIcon
        style={{ marginBottom: "24px" }}
      />

      <Space direction="vertical" size="large" style={{ width: "100%" }}>
        {/* Vite 内置环境变量 */}
        <Card
          title={
            <Space>
              <CodeOutlined />
              <span>Vite 环境变量</span>
              <Tag color={isDev() ? "green" : "blue"}>{getMode()}</Tag>
            </Space>
          }
        >
          <Table
            dataSource={envVars}
            columns={columns}
            pagination={false}
            size="small"
            rowKey="key"
          />

          {customEnvVarsList.length > 0 && (
            <>
              <Divider>自定义环境变量</Divider>
              <Table
                dataSource={customEnvVarsList}
                columns={columns}
                pagination={false}
                size="small"
                rowKey="key"
              />
            </>
          )}

          <Divider />

          <Paragraph type="secondary">
            <InfoCircleOutlined /> 环境变量说明:
            Vite提供了一些内置的环境变量，同时也支持通过.env文件配置自定义环境变量。
            自定义环境变量必须以VITE_开头才能在客户端代码中访问。
          </Paragraph>
        </Card>

        {/* 系统时间 */}
        <Card
          title={
            <Space>
              <ClockCircleOutlined />
              <span>系统时间</span>
            </Space>
          }
        >
          <Descriptions bordered>
            <Descriptions.Item label="当前时间" span={3}>
              <Text style={{ fontSize: "16px", fontWeight: "bold" }}>
                {formatDate(currentTime)}
              </Text>
            </Descriptions.Item>
            <Descriptions.Item label="ISO格式">
              {currentTime.toISOString()}
            </Descriptions.Item>
            <Descriptions.Item label="本地字符串">
              {currentTime.toString()}
            </Descriptions.Item>
            <Descriptions.Item label="Unix时间戳">
              {Math.floor(currentTime.getTime() / 1000)}
            </Descriptions.Item>
            <Descriptions.Item label="日期">
              {currentTime.toLocaleDateString()}
            </Descriptions.Item>
            <Descriptions.Item label="时间">
              {currentTime.toLocaleTimeString()}
            </Descriptions.Item>
            <Descriptions.Item label="时区">
              {Intl.DateTimeFormat().resolvedOptions().timeZone}
              (UTC{new Date().getTimezoneOffset() > 0 ? "-" : "+"}
              {Math.abs(new Date().getTimezoneOffset() / 60)})
            </Descriptions.Item>
          </Descriptions>
        </Card>

        {/* 浏览器信息 */}
        <Card
          title={
            <Space>
              <DesktopOutlined />
              <span>浏览器与系统信息</span>
            </Space>
          }
        >
          <Table
            dataSource={browserInfo}
            columns={columns}
            pagination={false}
            size="small"
            rowKey="key"
            expandable={{
              expandedRowRender: (record) => (
                <p style={{ margin: 0, padding: "12px" }}>
                  {record.name === "用户代理" && (
                    <Text type="secondary" style={{ wordBreak: "break-all" }}>
                      用户代理字符串包含了浏览器和操作系统的详细信息，可用于识别客户端环境。
                    </Text>
                  )}
                </p>
              ),
              rowExpandable: (record) => record.name === "用户代理",
            }}
          />

          <Divider />

          <Paragraph type="secondary">
            <InfoCircleOutlined />{" "}
            注意：浏览器可能会限制某些信息的访问，或者提供不准确的信息以保护用户隐私。
          </Paragraph>
        </Card>

        {/* 屏幕和设备信息 */}
        <Card
          title={
            <Space>
              <EnvironmentOutlined />
              <span>屏幕与设备信息</span>
            </Space>
          }
        >
          <Descriptions bordered>
            <Descriptions.Item label="屏幕分辨率" span={3}>
              {`${window.screen.width} × ${window.screen.height} 像素`}
            </Descriptions.Item>
            <Descriptions.Item label="可用屏幕尺寸">
              {`${window.screen.availWidth} × ${window.screen.availHeight} 像素`}
            </Descriptions.Item>
            <Descriptions.Item label="窗口尺寸">
              {`${window.innerWidth} × ${window.innerHeight} 像素`}
            </Descriptions.Item>
            <Descriptions.Item label="颜色深度">
              {window.screen.colorDepth} 位
            </Descriptions.Item>
            <Descriptions.Item label="设备像素比">
              {window.devicePixelRatio}
            </Descriptions.Item>
            <Descriptions.Item label="是否触摸设备">
              {"ontouchstart" in window ? (
                <Badge status="success" text="是" />
              ) : (
                <Badge status="default" text="否" />
              )}
            </Descriptions.Item>
            <Descriptions.Item label="媒体查询">
              {window.matchMedia("(prefers-color-scheme: dark)").matches ? (
                <Tag color="black">暗色模式</Tag>
              ) : (
                <Tag color="blue">亮色模式</Tag>
              )}

              {window.matchMedia("(prefers-reduced-motion: reduce)")
                .matches && <Tag color="orange">减弱动画</Tag>}
            </Descriptions.Item>
          </Descriptions>
        </Card>
      </Space>

      <div style={{ marginTop: "40px", textAlign: "center" }}>
        <Text type="secondary">系统信息刷新时间: {formatDate(new Date())}</Text>
      </div>
    </div>
  );
};

export default SystemInfoDemo;
